<template>
    <div>
        <template v-if="listener>0">
            <img class="upload-img" :src="image" alt="" @click="openApp" />
        </template>
        <template v-else>
            <van-uploader @oversize="onOversize" :after-read="afterRead">
                <img class="upload-img" :src="image" alt="" />
            </van-uploader>
        </template>
    </div>
</template>
<script>
import { upload } from "@/api/common";
import { is_weixin } from "@/utils/common.js";
export default {
    props: {
        image: {
            type: String,
            default: require("../../assets/Images/AppIcon/upload_picture.png")
        },
    },
    data() {
        return {
            listener: 0,
        };
    },
    mounted() {
        // 安卓
        if (window.jsListener && window.jsListener.doButton) {
            this.listener = 1;
        }
        //ios 交互 微信也有交互 多做判断
        if (is_weixin()) {
            //如果是微信执行的操作
        } else {
            //如果不是微信执行的操作
            if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.doButton) {
                this.listener = 1;
            }
        }
    },
    methods: {
        openApp() {
            if (this.listener == 1) {

                // 安卓
                if (window.jsListener) {
                    window.jsListener.doButton(1);
                }

                //ios 交互 微信也有交互 多做判断
                if (is_weixin()) {
                    //如果是微信执行的操作
                } else {
                    //如果不是微信执行的操作
                    if (window.webkit) {
                        if (window.webkit.messageHandlers) {
                            if (window.webkit.messageHandlers.doButton) {
                                window.webkit.messageHandlers.doButton.postMessage("1");
                            }
                        }
                    }
                }
                window.doButtonResult = this.doButtonResult;
            }
        },
        afterRead(file) {
            let params = new FormData(); //创建form对象
            params.append("file", file.file);
            upload(params)
                .then((res) => {
                    var array = [];
                    res.data.forEach((item) => {
                        array.push(item.FilePath);
                    });
                    this.$emit("after-read", array.join(";"));
                })
                .catch((err) => {
                    console.log("err", err);
                });
        },
        onOversize(file) {
            this.$toast("文件大小不能超过 2M");
        },

        doButtonResult(key, result) {
            if (result) {
                this.$emit("after-read", result);
            }
        },
    },
};
</script>
<style lang="less" scoped>
.upload-img {
    position: relative;
    width: 60px;
    height: 60px;
}
</style>